package com.jl15988.pguard.platform;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

/**
 * Linux平台进程实现
 *
 * @author jl15988
 * @since 1.0.0
 */
@Slf4j
public class LinuxProcessPlatform implements ProcessPlatform {
    @Override
    public Process createProcess(String command, String workingDirectory, String[] environmentVariables) throws IOException {
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command("sh", "-c", command);

        if (workingDirectory != null) {
            processBuilder.directory(new java.io.File(workingDirectory));
        }

        if (environmentVariables != null) {
            processBuilder.environment().putAll(java.util.Arrays.stream(environmentVariables)
                    .map(s -> s.split("="))
                    .collect(java.util.stream.Collectors.toMap(arr -> arr[0], arr -> arr[1])));
        }

        return processBuilder.start();
    }

    @Override
    public Process monitorProcess(long pid) throws IOException {
        return Runtime.getRuntime().exec("top -p " + pid + " -b -d 1");
    }

    @Override
    public boolean killProcess(long pid) throws Exception {
        Process process = Runtime.getRuntime().exec("kill -9 " + pid);
        return process.waitFor(3000, TimeUnit.MILLISECONDS) &&
                process.exitValue() == 0;
    }

    @Override
    public boolean isProcessExist(long pid) {
        try {
            Process process = Runtime.getRuntime().exec("ps -p " + pid);
            return process.waitFor() == 0;
        } catch (IOException | InterruptedException e) {
            log.error("检查Linux进程存在失败", e);
            return false;
        }
    }

    @Override
    public long findProcessIdByPort(int port) {
        try {
            Process process = Runtime.getRuntime().exec("lsof -i:" + port + " -t");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = reader.readLine();
            if (line != null && !line.trim().isEmpty()) {
                return Long.parseLong(line.trim());
            }
        } catch (Exception e) {
            log.error("查找Linux端口对应进程失败", e);
        }
        return -1;
    }

    @Override
    public String getPlatformName() {
        return "Linux";
    }

    @Override
    public PlatformProcessInfo getProcessInfo(long pid) throws IOException {
        Process p = Runtime.getRuntime().exec("ps -p " + pid + " -o %cpu,%mem,rss");
        double cpuUsage = 0;
        long memoryUsage = 0;

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            reader.readLine(); // 跳过标题行
            String line = reader.readLine();
            if (line != null) {
                String[] parts = line.trim().split("\\s+");
                cpuUsage = Double.parseDouble(parts[0]);
                memoryUsage = Long.parseLong(parts[2]) * 1024; // 转换为字节
            }
        }

        return new PlatformProcessInfo(cpuUsage, memoryUsage);
    }
}
